package com.bluesky.admin.controller.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.bluesky.common.config.AppConfig;
import com.bluesky.common.utils.FileUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 通用common 前端控制器
 * </p>
 *
 * @author Kevin
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @GetMapping("/download")
    @SneakyThrows
    public void download(@RequestParam String filename, HttpServletResponse response) {
        String realFileName = FileUtils.formatFilename(filename);
        String filepath = AppConfig.getTemp() + "/" + filename;
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, realFileName);
        // 处理window路径双斜杠的问题
        filepath = StrUtil.replace(filepath, "\\", "/");
        FileUtil.writeToStream(filepath, response.getOutputStream());
    }

}
